const { createProxyMiddleware } = require('http-proxy-middleware');
const { httpRoutes } = require('../config/routes');

// 创建代理对象映射
const proxies = {};

httpRoutes.forEach(route => {
  proxies[route.path] = createProxyMiddleware({
    target: route.target,
    changeOrigin: true,
    pathRewrite: { [`^${route.path}`]: '' },
    onProxyReq: (proxyReq, req, res) => {
      proxyReq.setHeader('X-Gateway-Request-ID', Math.random().toString(36).substring(2, 15));
      // 将JWT令牌传递给后端服务
      if (req.user) {
        proxyReq.setHeader('X-User', JSON.stringify(req.user));
      }
    },
    onError: (err, req, res) => {
      res.status(503).json({ error: `${route.name} is unavailable` });
    }
  });
});

module.exports = proxies;